const router = require("express").Router();
// const request = require("request");
const atwork = require("atwork");
const config = require("../config/constant").config;
const apps = require("../config/apps-info");

const getCurrentApp = function(req){
	const reqType = req.params.type;
	const tragetApp = apps.find((item)=>{
		return item.type == reqType;
	});
	// throw new Error();
	return {
		clientId: tragetApp.clientId,
		clientSecret: tragetApp.clientSecret
	}
}

const getAtworkInstance = function(req) {
	// const config = require("../config/constant");
	const atwork = require("atwork");
	const currentApp = getCurrentApp(req);
	// 测试环境org_id 18590d66-26fe-4e78-9344-496370670ccf
	// 正式环境org_id 1df94799-fd32-49c3-b6d1-f7c9eb6caf49
	const param = {
		clientId: currentApp.clientId,
		clientSecret: currentApp.clientSecret,
		adminServer: config.apiServer.internal,
		domainId: req.query.domainId || "rfchina",
		orgId: req.query.orgId || "1df94799-fd32-49c3-b6d1-f7c9eb6caf49"
	};
	const instance = atwork(param);
	return instance;
};


const proxyRequest = function(req, params){
	const options = {
		method: "POST",
		url: config.apiServer.internal + "/rf-china/userAppList",
		// url: "http://172.16.1.160:9010/applist.json",
		json: true,
		body: {
			"account": params.user_name
		}
	};
	return getAtworkInstance(req).send(options);
};

const getAppListByUser = function(req, res){
	console.log(req.query);
	console.log(req.params);
	// const finishedMock = {"status":0,"message":"Everything is ok.","result":[{"id":"d0bb218aee","title":"已办","publish_time":"83013801","link_url":"https://baidu.com","image_url":"https://dn-jsjpub.qbox.me/ic/20161126141947_1b4cb2@iclarge"}]};
	// const mock = {"status":0,"message":"Everything is ok.","result":[{"id":"d0bb218aee","title":"待办","publish_time":"83013801","link_url":"https://baidu.com","image_url":"https://dn-jsjpub.qbox.me/ic/20161126141947_1b4cb2@iclarge"}]};
	// const mockError = {"status": 400, "message": "error"};

	// const subscription_id = (req.query.tabType)?req.query.tabType:req.params.type; //有子项，拿子项type,没有拿params的type
	const params = {
		user_name: req.query.user
	}
	proxyRequest(req, params).then(workplusRes=>{
		console.log(workplusRes);
		res.json(workplusRes);
	});

	//console.log(applistData);
	//res.json(applistData);

	// if(req.query.tabType && req.query.tabType == "finished"){
	// 	res.json(finishedMock);
	// }else{
	// 	res.json(mock)
	// }
}

router.get("/:type", getAppListByUser);
module.exports = router;